import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:lmmi/common/index.dart';
class LoginPage extends ConsumerStatefulWidget {
  const LoginPage({super.key});

  @override
  ConsumerState<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends ConsumerState<LoginPage> {
  final TextEditingController usernameController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

  @override
  void dispose() {
    usernameController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  /// 处理登录
  Future<void> _handleLogin() async {
    final username = usernameController.text.trim();
    final password = passwordController.text.trim();

    // 基本验证
    if (username.isEmpty) {
      _showErrorMessage('please input username');
      return;
    }

    if (password.isEmpty) {
      _showErrorMessage('please input password');
      return;
    }

    // 显示加载状态
    _showLoadingDialog();

    final success = await ref
        .read(userProvider.notifier)
        .login(username, password);

    // 隐藏加载对话框
    if (mounted) {
      Navigator.of(context).pop();
    }

    if (success) {
      // 登录成功，跳转到主页
      if (mounted) {
        context.push(AppRoutes.main);
      }
    } else {
      // 登录失败，显示错误信息
      if (mounted) {
        final error = ref.read(userProvider).error;
        _showErrorMessage(error ?? 'login failed');
      }
    }
  }

  /// 处理苹果登录
  Future<void> _handleAppleSignIn() async {
    // 显示加载状态
    _showLoadingDialog();

    final success = await ref.read(userProvider.notifier).signInWithApple();

    // 隐藏加载对话框
    if (mounted) {
      Navigator.of(context).pop();
    }

    if (success) {
      // 登录成功，跳转到主页
      if (mounted) {
        context.push(AppRoutes.main);
      }
    } else {
      // 登录失败，显示错误信息
      if (mounted) {
        final error = ref.read(userProvider).error;
        // 如果是用户取消，不显示错误信息
        if (error != null && !error.contains('canceled')) {
          _showErrorMessage(error);
        }
      }
    }
  }

  /// 显示错误信息
  void _showErrorMessage(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.red,
          duration: const Duration(seconds: 3),
        ),
      );
    }
  }

  /// 显示加载对话框
  void _showLoadingDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFF8C00)),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: SingleChildScrollView(
          child: Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            clipBehavior: Clip.antiAlias,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment(0.50, -0.00),
                end: Alignment(0.50, 1.00),
                colors: [const Color(0xFFFFBB67), Colors.white],
              ),
            ),
            child: SafeArea(
              bottom: false,
              top: false,
              child: Stack(
                children: [
                  Positioned(
                    right: -55.w,
                    top: -25.h,
                    child: Container(
                      width: 194.w,
                      height: 194.h,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage(MyImages.nativeBgLeft),
                          fit: BoxFit.contain,
                        ),
                      ),
                    ),
                  ),
                  Positioned(
                    left: -50.w,
                    top: 135.h,
                    child: Container(
                      width: 194.w,
                      height: 194.h,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage(MyImages.nativeRight),
                          fit: BoxFit.contain,
                        ),
                      ),
                    ),
                  ),
                  Positioned(
                    top: 325.h,
                    left: 31.w,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Welcome',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: const Color(0xFFFF8C00),
                            fontSize: 36.sp,
                            fontFamily: 'PoetsenOne',
                            fontWeight: FontWeight.w400,
                          ),
                        ),

                        Text(
                          'Login to your account to continue',
                          style: TextStyle(
                            color: const Color(0xFFFF8C00),
                            fontSize: 14.sp,
                            fontFamily: 'Manrope',
                            fontWeight: FontWeight.w400,
                            height: 1.60,
                            letterSpacing: 0.28,
                          ),
                        ),
                      ],
                    ),
                  ),

                  Positioned(
                    bottom: 57.h,
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 32.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          CustomTextField(
                            controller: usernameController,
                            hintText: 'Input username',
                            width: 311.w,
                            height: 46.h,
                            keyboardType: TextInputType.text,
                            maxLength: 6,
                            onChanged: (value) {
                              usernameController.text = value;
                            },
                          ),

                          SizedBox(height: 12.h),

                          CustomTextField(
                            controller: passwordController,
                            hintText: 'Input password',
                            width: 311.w,
                            height: 46.h,
                            obscureText: true,
                          ),

                          SizedBox(height: 6.h),

                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text.rich(
                                TextSpan(
                                  children: [
                                    TextSpan(
                                      text: 'Don’t have an account?',
                                      style: TextStyle(
                                        color: Colors.black.withValues(
                                          alpha: 0.26,
                                        ),
                                        fontSize: 12.sp,
                                        fontFamily: 'PingFang SC',
                                        fontWeight: FontWeight.w400,
                                      ),
                                    ),
                                    TextSpan(
                                      text: ' ',
                                      style: TextStyle(
                                        color: const Color(0x0045204C),
                                        fontSize: 12.sp,
                                        fontFamily: 'PingFang SC',
                                        fontWeight: FontWeight.w400,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              GestureDetector(
                                onTap: () {
                                  context.push(AppRoutes.register);
                                },
                                child: Text(
                                  'Sign up',
                                  style: TextStyle(
                                    color: Colors.black.withValues(alpha: 0.72),
                                    fontSize: 12.sp,
                                    fontFamily: 'PingFang SC',
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ),
                            ],
                          ),

                          SizedBox(height: 24.h),

                          InkWell(
                            onTap: _handleLogin,
                            child: Container(
                              width: 315.w,
                              height: 48.h,
                              clipBehavior: Clip.antiAlias,
                              decoration: ShapeDecoration(
                                color: const Color(0xFFFF8C00),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10.r),
                                ),
                              ),
                              child: Center(
                                child: Text(
                                  'login',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 14.sp,
                                    fontFamily: 'Airbnb Cereal App',
                                    fontWeight: FontWeight.w700,
                                  ),
                                ),
                              ),
                            ),
                          ),

                          SizedBox(height: 10.h),

                          GestureDetector(
                            onTap: _handleAppleSignIn,
                            child: Container(
                              width: 315.w,
                              height: 58.h,
                              decoration: ShapeDecoration(
                                color: Colors.black,
                                shape: RoundedRectangleBorder(
                                  side: BorderSide(
                                    width: 1,
                                    color: Colors.white.withValues(alpha: 0.44),
                                  ),
                                  borderRadius: BorderRadius.circular(10.r),
                                ),
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Icon(
                                    Icons.apple,
                                    color: Colors.white,
                                    size: 18.sp,
                                  ),
                                  Text(
                                    'Continue with Apple',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 14.sp,
                                      fontFamily: 'PingFang SC',
                                      fontWeight: FontWeight.w400,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),

                          SizedBox(height: 10.h),

                          Text.rich(
                            TextSpan(
                              children: [
                                TextSpan(
                                  text: 'By Continuing you agree with',
                                  style: TextStyle(
                                    color: Colors.black.withValues(alpha: 0.56),
                                    fontSize: 10.sp,
                                    fontFamily: 'PingFang HK',
                                    fontWeight: FontWeight.w400,
                                    height: 1.60,
                                  ),
                                ),
                                TextSpan(
                                  text: ' ',
                                  style: TextStyle(
                                    color: Colors.black.withValues(alpha: 0.60),
                                    fontSize: 10.sp,
                                    fontFamily: 'PingFang HK',
                                    fontWeight: FontWeight.w400,
                                    height: 1.60,
                                  ),
                                ),
                                TextSpan(
                                  text: 'Terms of Service',
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      UrlUtils().openUrl(UrlUtils.TERMS_OF_SERVICE);
                                    },
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 10.sp,
                                    fontFamily: 'PingFang HK',
                                    fontWeight: FontWeight.w400,
                                    decoration: TextDecoration.underline,
                                    height: 1.60,
                                  ),
                                ),
                                TextSpan(
                                  text: ' ',
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 10.sp,
                                    fontFamily: 'PingFang HK',
                                    fontWeight: FontWeight.w400,
                                    height: 1.60,
                                  ),
                                ),
                                TextSpan(
                                  text: '&',
                                  style: TextStyle(
                                    color: Colors.black.withValues(alpha: 0.56),
                                    fontSize: 10.sp,
                                    fontFamily: 'PingFang HK',
                                    fontWeight: FontWeight.w400,
                                    height: 1.60,
                                  ),
                                ),
                                TextSpan(
                                  text: ' ',
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 10.sp,
                                    fontFamily: 'PingFang HK',
                                    fontWeight: FontWeight.w400,
                                    height: 1.60,
                                  ),
                                ),
                                TextSpan(
                                  text: 'Privacy Policy',
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      UrlUtils().openUrl(UrlUtils.PRIVACY_POLICY);
                                    },
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 10.sp,
                                    fontFamily: 'PingFang HK',
                                    fontWeight: FontWeight.w400,
                                    decoration: TextDecoration.underline,
                                    height: 1.60,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
